<template>
  <div class="merchant-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">
        <i class="el-icon-s-shop"></i>
        商家管理
      </h2>
      <p class="page-description">查看您负责的商家列表，按入驻时间倒序排列</p>
    </div>

    <!-- 搜索筛选 -->
    <div class="search-section">
      <el-card>
        <el-form :model="searchForm" :inline="true" class="search-form">
          <el-form-item label="商家名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入商家名称"
              clearable
              style="width: 200px">
            </el-input>
          </el-form-item>
          <el-form-item label="入驻时间">
            <el-date-picker
              v-model="searchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd"
              style="width: 240px">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">查询</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <!-- 商家列表 -->
    <div class="merchant-list">
      <el-card>
        <div slot="header" class="card-header">
          <span>商家列表</span>
          <div class="header-actions">
            <el-button
              icon="el-icon-refresh"
              @click="loadData">
              刷新
            </el-button>
          </div>
        </div>

        <configurable-table
          :columns="tableColumns"
          :data="merchantList"
          :loading="loading"
          :show-pagination="true"
          :current-page.sync="pagination.current"
          :page-size.sync="pagination.size"
          :pagination-total="pagination.total"
          @page-change="loadData"
          stripe>
          <!-- 状态列 -->
          <template #status="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ row.statusText }}
            </el-tag>
          </template>
          <!-- 入驻时间列 -->
          <template #createTime="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
          <!-- 操作列 -->
          <template #actions="{ row }">
            <el-button
              type="text"
              size="small"
              @click="handleViewDetail(row)">
              查看详情
            </el-button>
          </template>
        </configurable-table>
      </el-card>
    </div>

    <!-- 商家详情对话框 -->
    <el-dialog
      :visible.sync="detailDialogVisible"
      width="800px"
      :close-on-click-modal="false"
      custom-class="view-dialog"
      top="5vh">

      <div slot="title" class="dialog-title-wrapper">
        <i class="el-icon-s-shop"></i>
        <span>商家详情</span>
      </div>

      <div class="detail-content" v-if="selectedMerchant">
        <!-- 头部信息卡片 -->
        <div class="detail-header">
          <div class="avatar-section">
            <div class="avatar-circle">
              <img v-if="selectedMerchant.avatar" :src="selectedMerchant.avatar" class="avatar-img" alt="商家头像" />
              <i v-else class="el-icon-s-shop"></i>
            </div>
            <div class="status-badge">
              <el-tag :type="getStatusType(selectedMerchant.status)" size="small">
                {{ selectedMerchant.statusText }}
              </el-tag>
            </div>
          </div>
          <div class="header-info">
            <h3 class="merchant-name">{{ selectedMerchant.name }}</h3>
            <div class="merchant-phone-display">
              <i class="el-icon-phone"></i>
              <span>{{ selectedMerchant.phone }}</span>
            </div>
          </div>
        </div>

        <!-- 基本信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-user"></i>
            <span>基本信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-postcard"></i>
                <span>商家ID</span>
              </div>
              <div class="info-value">{{ selectedMerchant.id }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-user-solid"></i>
                <span>联系人</span>
              </div>
              <div class="info-value">{{ selectedMerchant.contactPerson || '未填写' }}</div>
            </div>
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-postcard"></i>
                <span>营业执照号</span>
              </div>
              <div class="info-value">{{ maskIdNo(selectedMerchant.businessLicenseNo) }}</div>
            </div>
            <div class="info-item full-width">
              <div class="info-label">
                <i class="el-icon-location"></i>
                <span>商家地址</span>
              </div>
              <div class="info-value">{{ selectedMerchant.address || '未填写' }}</div>
            </div>
          </div>
        </div>

        <!-- 时间信息 -->
        <div class="info-section">
          <div class="section-title">
            <i class="el-icon-time"></i>
            <span>时间信息</span>
          </div>
          <div class="info-grid">
            <div class="info-item">
              <div class="info-label">
                <i class="el-icon-date"></i>
                <span>入驻时间</span>
              </div>
              <div class="info-value time-value">{{ formatDateTime(selectedMerchant.createTime) }}</div>
            </div>
            <div class="info-item" v-if="selectedMerchant.updateTime">
              <div class="info-label">
                <i class="el-icon-refresh"></i>
                <span>更新时间</span>
              </div>
              <div class="info-value time-value">{{ formatDateTime(selectedMerchant.updateTime) }}</div>
            </div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="detailDialogVisible = false" size="medium">
          <i class="el-icon-close"></i>
          关闭
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { getSalesmanMerchantPage, getSalesmanMerchantDetail } from '@/api/salesman/merchant-management'

export default {
  name: 'SalesmanMerchantManagement',
  data() {
    return {
      // 搜索表单
      searchForm: {
        name: '',
        dateRange: []
      },

      // 表格数据
      merchantList: [],
      loading: false,

      // 分页（每页10条）
      pagination: {
        current: 1,
        size: 10,
        total: 0
      },

      // 表格列配置
      tableColumns: [
        { prop: 'id', label: '商家ID', minWidth: 80 },
        { prop: 'name', label: '商家名称', minWidth: 150 },
        { prop: 'contactPerson', label: '联系人', minWidth: 120 },
        { prop: 'phone', label: '联系电话', minWidth: 130 },
        { prop: 'address', label: '商家地址', minWidth: 200, showOverflowTooltip: true },
        { prop: 'businessLicenseNo', label: '营业执照号', minWidth: 150 },
        { prop: 'status', label: '状态', minWidth: 100, slot: 'status' },
        { prop: 'createTime', label: '入驻时间', minWidth: 150, slot: 'createTime' },
        { prop: 'actions', label: '操作', minWidth: 120, slot: 'actions', fixed: 'right' }
      ],

      // 详情对话框
      detailDialogVisible: false,
      selectedMerchant: null
    }
  },

  mounted() {
    this.loadData()
  },

  methods: {
    // 加载数据（按入驻时间倒序排列）
    async loadData() {
      this.loading = true
      try {
        const params = {
          pageIndex: this.pagination.current,
          pageSize: this.pagination.size,
          name: this.searchForm.name || '',
          startTime: this.searchForm.dateRange && this.searchForm.dateRange[0] ? this.searchForm.dateRange[0] + ' 00:00:00' : '',
          endTime: this.searchForm.dateRange && this.searchForm.dateRange[1] ? this.searchForm.dateRange[1] + ' 23:59:59' : '',
          orderBy: 'createTime', // 按入驻时间排序
          order: 'desc' // 倒序排列
        }

        Logger.log('=== 业务员商家管理API请求调试 ===')
        Logger.log('请求参数:', params)

        const response = await getSalesmanMerchantPage(params)
        Logger.log('商家列表响应:', response.data)

        if (response.code === 0 && response.data) {
          this.merchantList = response.data.list || []
          this.pagination.total = response.data.total || 0
        } else {
          this.merchantList = []
          this.pagination.total = 0
          if (response.data && response.data.msg) {
            Logger.log('商家查询结果:', response.data.msg)
          }
        }

      } catch (error) {
        Logger.error('加载商家数据失败:', error)
        this.merchantList = []
        this.pagination.total = 0
        this.$message.error('加载商家数据失败')
      } finally {
        this.loading = false
      }
    },

    // 搜索
    handleSearch() {
      this.pagination.current = 1
      this.loadData()
    },

    // 重置
    handleReset() {
      this.searchForm = {
        name: '',
        dateRange: []
      }
      this.pagination.current = 1
      this.loadData()
    },

    // 查看详情
    async handleViewDetail(row) {
      try {
        const response = await getSalesmanMerchantDetail(row.id)
        Logger.log('商家详情响应:', response.data)

        if (response.code === 0 && response.data) {
          this.selectedMerchant = response.data
          this.detailDialogVisible = true
        } else {
          this.$message.error('获取商家详情失败')
        }
      } catch (error) {
        Logger.error('获取商家详情失败:', error)
        this.$message.error('获取商家详情失败')
      }
    },


    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '-'
      return new Date(dateTime).toLocaleString()
    },

    // 获取状态类型
    getStatusType(status) {
      const statusMap = {
        0: 'success', // 正常
        1: 'danger', // 停用
      }
      return statusMap[status] || 'success'
    },

    // 遮罩身份证号
    maskIdNo(idNo) {
      if (!idNo) return '未填写'
      if (idNo.length < 10) return idNo
      return idNo.substring(0, 6) + '****' + idNo.substring(idNo.length - 4)
    },
  }
}
</script>

<style scoped>
.merchant-management-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 20px;
}

.page-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 8px 0;
  display: flex;
  align-items: center;
}

.page-description {
  color: #606266;
  margin: 0;
  font-size: 14px;
}

.search-section {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.merchant-list {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions .el-button {
  margin-left: 10px;
}


/* ===== 对话框标题样式 ===== */
.dialog-title-wrapper {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.dialog-title-wrapper i {
  margin-right: 8px;
  font-size: 20px;
  color: #409eff;
}

/* ===== 商家详情对话框样式 ===== */
.detail-content {
  padding: 0;
  max-height: 70vh;
  overflow-y: auto;
}

/* 头部信息区域 */
.detail-header {
  display: flex;
  align-items: center;
  gap: 24px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
  margin-bottom: 24px;
  position: relative;
  overflow: hidden;
}

.detail-header::before {
  content: '';
  position: absolute;
  top: -50%;
  right: -50px;
  width: 200px;
  height: 200px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 50%;
}

.detail-header::after {
  content: '';
  position: absolute;
  bottom: -50px;
  left: -50px;
  width: 150px;
  height: 150px;
  background: rgba(255, 255, 255, 0.08);
  border-radius: 50%;
}

/* 头像区域 */
.avatar-section {
  position: relative;
  z-index: 1;
}

.avatar-circle {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: linear-gradient(135deg, #fff 0%, #f5f5f5 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border: 4px solid rgba(255, 255, 255, 0.3);
}

.avatar-circle i {
  font-size: 36px;
  color: #667eea;
}

.avatar-circle .avatar-img {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}

.status-badge {
  position: absolute;
  bottom: -5px;
  right: -5px;
  z-index: 2;
}

.status-badge .el-tag {
  border-radius: 12px;
  padding: 4px 10px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 头部信息文字 */
.header-info {
  flex: 1;
  color: white;
  z-index: 1;
}

.merchant-name {
  margin: 0 0 12px 0;
  font-size: 24px;
  font-weight: 600;
  color: white;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.merchant-phone-display {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20px;
  backdrop-filter: blur(10px);
  font-weight: 600;
  font-size: 14px;
}

.merchant-phone-display i {
  font-size: 16px;
}

/* 信息区块 */
.info-section {
  background: #ffffff;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.info-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 14px 20px;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-bottom: 1px solid #e4e7ed;
  font-weight: 600;
  font-size: 14px;
  color: #303133;
}

.section-title i {
  font-size: 16px;
  color: #409eff;
}

.info-grid {
  padding: 20px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-item.full-width {
  grid-column: 1 / -1;
}

.info-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: #909399;
  font-weight: 500;
}

.info-label i {
  font-size: 14px;
  color: #c0c4cc;
}

.info-value {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
  min-height: 36px;
  display: flex;
  align-items: center;
}

.info-value:hover {
  background: #f0f2f5;
  border-color: #d4d7dc;
}

.time-value {
  font-size: 13px;
  color: #606266;
}

/* ===== 对话框底部样式 ===== */
.dialog-footer {
  text-align: center;
  padding: 16px 0 0;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer .el-button {
  min-width: 100px;
  padding: 10px 20px;
  font-weight: 500;
}

.dialog-footer .el-button i {
  margin-right: 4px;
}

/* ===== 响应式优化 ===== */
@media screen and (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }

  .detail-header {
    flex-direction: column;
    text-align: center;
  }

  .avatar-circle {
    width: 70px;
    height: 70px;
  }

  .avatar-circle i {
    font-size: 32px;
  }

  .merchant-name {
    font-size: 20px;
  }
}

/* ===== 自定义滚动条 ===== */
.detail-content::-webkit-scrollbar {
  width: 6px;
}

.detail-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.detail-content::-webkit-scrollbar-thumb {
  background: #c0c4cc;
  border-radius: 3px;
}

.detail-content::-webkit-scrollbar-thumb:hover {
  background: #909399;
}
</style>
